package com.sugar.real.estate.module.business.service.buildhouse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.real.estate.framework.common.pojo.PageResult;
import com.sugar.real.estate.framework.common.util.object.BeanUtils;
import com.sugar.real.estate.module.business.controller.admin.buildhouse.vo.BuildHousePageReqVO;
import com.sugar.real.estate.module.business.controller.admin.buildhouse.vo.BuildHouseSaveReqVO;
import com.sugar.real.estate.module.business.controller.app.buildhouse.vo.AppBuildHouseDetailRespVO;
import com.sugar.real.estate.module.business.controller.app.buildhouse.vo.AppBuildHouseSimpleRespVO;
import com.sugar.real.estate.module.business.dal.dataobject.buildhouse.BuildHouseDO;
import com.sugar.real.estate.module.business.dal.dataobject.readyhouse.ReadyHouseDO;
import com.sugar.real.estate.module.business.dal.dataobject.userbuildingconsult.UserBuildingConsultDO;
import com.sugar.real.estate.module.business.dal.mysql.buildhouse.BuildHouseMapper;
import com.sugar.real.estate.module.business.dal.mysql.userbuildingconsult.UserBuildingConsultMapper;
import com.sugar.real.estate.module.business.util.I18nUtil;
import com.sugar.real.estate.module.infra.controller.admin.file.vo.file.FileUploadReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sugar.real.estate.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.real.estate.module.business.enums.ErrorCodeConstants.*;

/**
 * 建房 Service 实现类
 *
 * @author Ysugar
 */
@Slf4j
@Service
@Validated
public class BuildHouseServiceImpl implements BuildHouseService {

    @Resource
    private BuildHouseMapper buildHouseMapper;
    @Resource
    private UserBuildingConsultMapper userBuildingConsultMapper;

    @Override
    public Long createBuildHouse(BuildHouseSaveReqVO createReqVO) {
        // 插入
        BuildHouseDO buildHouse = BeanUtils.toBean(createReqVO, BuildHouseDO.class);
        buildHouseMapper.insert(buildHouse);
        // 返回
        return buildHouse.getId();
    }

    @Override
    public void updateBuildHouse(BuildHouseSaveReqVO updateReqVO) {
        // 校验存在
        validateBuildHouseExists(updateReqVO.getId());
        // 更新
        BuildHouseDO updateObj = BeanUtils.toBean(updateReqVO, BuildHouseDO.class);
        buildHouseMapper.updateById(updateObj);
    }

    @Override
    public void deleteBuildHouse(Long id) {
        // 校验存在
        validateBuildHouseExists(id);
        // 删除
        buildHouseMapper.deleteById(id);
        //删除用户咨询
        userBuildingConsultMapper.delete(Wrappers.<UserBuildingConsultDO>lambdaQuery()
                .eq(UserBuildingConsultDO::getFollowId, id).eq(UserBuildingConsultDO::getType, 2));
    }

    @Override
        public void deleteBuildHouseListByIds(List<Long> ids) {
        // 校验存在
        validateBuildHouseExists(ids);
        // 删除
        buildHouseMapper.deleteByIds(ids);
        }

    private void validateBuildHouseExists(List<Long> ids) {
        List<BuildHouseDO> list = buildHouseMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUILD_HOUSE_NOT_EXISTS);
        }
    }

    private void validateBuildHouseExists(Long id) {
        if (buildHouseMapper.selectById(id) == null) {
            throw exception(BUILD_HOUSE_NOT_EXISTS);
        }
    }

    @Override
    public BuildHouseDO getBuildHouse(Long id) {
        return buildHouseMapper.selectById(id);
    }

    @Override
    public PageResult<BuildHouseDO> getBuildHousePage(BuildHousePageReqVO pageReqVO) {
        return buildHouseMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AppBuildHouseSimpleRespVO> appGetBuildHouseAll() {
        return BeanUtils.toBean(buildHouseMapper.selectList(), AppBuildHouseSimpleRespVO.class,
                o -> o.setLocation(I18nUtil.getMessage(o, "getLocation"))
                        .setShowImage(o.getShowImages().get(0)));
    }

    @Override
    public AppBuildHouseDetailRespVO appGetBuildHouse(Long id) {
        BuildHouseDO buildHouseDO = buildHouseMapper.selectById(id);
        if (Objects.isNull(buildHouseDO))
            return null;
        AppBuildHouseDetailRespVO respVO = BeanUtils.toBean(buildHouseDO, AppBuildHouseDetailRespVO.class);
        respVO.setLocation(I18nUtil.getMessage(respVO, "getLocation"))
                .setContent(I18nUtil.getMessage(respVO, "getContent"));

        // 更新查看数量
        buildHouseMapper.update(BuildHouseDO::getId, buildHouseDO.getId(), BuildHouseDO::getLookCount, buildHouseDO.getLookCount() + 1);

        return respVO;
    }

    @Override
    public void importExcel(FileUploadReqVO uploadReqVO) {
        final int[] i = {2};

        try {
            EasyExcel.read(uploadReqVO.getFile().getInputStream(), new ReadListener<Map<Integer, String>>() {
                @Override
                public void invoke(Map<Integer, String> data, AnalysisContext context) {
                    try {
                        BuildHouseDO buildHouse = new BuildHouseDO();
                        buildHouse.setLocationZhCn(data.get(0));
                        buildHouse.setLocationEnUs(data.get(1));
                        buildHouse.setShowImages(Arrays.stream(data.get(2).split(",")).collect(Collectors.toList()));
                        String data3 = data.get(3);
                        if (StrUtil.isNotBlank(data3))
                            buildHouse.setLandArea(new BigDecimal(data3));
                        buildHouse.setContentZhCn(data.get(4));
                        buildHouse.setContentEnUs(data.get(5));

                        // 插入
                        buildHouseMapper.insert(buildHouse);
                        i[0] = i[0] + 1;
                    }catch (Throwable e){
                        log.error("导入现房数据失败：", e);
                        throw exception(SERVER_BUSY);
                    }
                }

                // 读取完毕
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                }
            }).sheet().doRead();
        }catch (Throwable e){
            throw exception(IMPORT_EXCEL_ERROR, i[0]);
        }
    }
}